package com.yunyao.web.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.yunyao.common.core.BaseContext;
import com.yunyao.common.core.UserInfoRequest;
import com.yunyao.common.dto.excel.ContractExcelDto;
import com.yunyao.common.dto.excel.ProjectOrderExcelDto;
import com.yunyao.common.dto.excel.SupplyExcelDto;
import com.yunyao.common.dto.supplier.ContractDto;
import com.yunyao.common.dto.SoSupplyDto;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.YResult;
import com.yunyao.framework.dto.contract.ContractWirePaySaveDto;
import com.yunyao.framework.dto.file.FileInfoDto;
import com.yunyao.framework.dto.soSupply.SoSupplyMaterialDeletedDto;
import com.yunyao.framework.dto.soSupply.SoSupplyMaterialDto;
import com.yunyao.framework.dto.soSupply.SoSupplyMaterialSaveDto;
import com.yunyao.framework.dto.soSupply.SosupplySaveDto;
import com.yunyao.framework.service.SoSupplyOrderService;
import com.yunyao.framework.service.SoSupplyService;
import com.yunyao.framework.vo.contract.ContractNodePayVO;
import com.yunyao.framework.vo.contract.ContractWirePayVO;
import com.yunyao.framework.vo.sosyupply.SoSupplinfoVO;
import com.yunyao.framework.vo.sosyupply.SoSupplyMaterialVO;
import com.yunyao.framework.vo.sosyupply.SoSupplyVO;
import com.yunyao.web.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/sosupply")
public class SoSupplyController {
    @Autowired
    private SoSupplyService soSupplyService;
    @Autowired
    private SoSupplyOrderService soSupplyOrderService;


    /**
     * 获取验收清单列表
     *
     * @param soSupplyDto
     * @return
     */
    @GetMapping("/list")
    public YResult<PageResult<SoSupplyVO>> getList(SoSupplyDto soSupplyDto) {
        return soSupplyService.pageList(soSupplyDto);
    }


    /**
     * 获取验收清单详情信息
     *
     * @param id
     * @return
     */
    @GetMapping("/info")
    public YResult<SoSupplinfoVO> getInfo(String id) {

        return soSupplyService.getSoSupplyById(id);
    }

    /**
     * 保存验收清单信息
     *
     * @param saveDto
     * @return
     */
    @PostMapping("/save")
    public YResult<String> saveInfo(@RequestBody SosupplySaveDto saveDto) {
        return soSupplyService.saveInfo(saveDto);
    }

    /**
     * 获取验收材料列表
     *
     * @return
     */
    @GetMapping("/material/list")
    public YResult<PageResult<SoSupplyMaterialVO>> getContractMaterialList(SoSupplyMaterialDto soSupplyMaterialDto) {
        return soSupplyOrderService.getPoSupplyMaterialList(soSupplyMaterialDto);
    }

    /**
     * 获取合同付款方式信息
     *
     * @param contractDto
     * @return
     */
    @GetMapping("/wire/pay/info")
    public YResult<ContractWirePayVO> getWirePayInfo(ContractDto contractDto) {
        return soSupplyOrderService.getWirePayInfo(contractDto);
    }

    /**
     * 获取合同付款方式节点信息列表
     *
     * @param contractDto
     * @return
     */
    @GetMapping("/node/pay/list")
    public YResult<PageResult<ContractNodePayVO>> getContractNodePayList(ContractDto contractDto) {
        return soSupplyOrderService.getContractNodePayList(contractDto);
    }

    /**
     * 保存合同付款方式信息
     *
     * @param saveDto
     * @return
     */
    @PostMapping("/wire/pay/save")
    public YResult<String> savePayInfo(@RequestBody ContractWirePaySaveDto saveDto) {
        return soSupplyOrderService.savePayInfo(saveDto);
    }

    /**
     * 保存合同材料信息
     *
     * @param saveDto
     * @return
     */
    @PostMapping("/material/save")
    public YResult<String> saveMaterialInfo(@RequestBody SoSupplyMaterialSaveDto saveDto) {
        return soSupplyOrderService.saveMaterialInfo(saveDto);
    }

    /**
     * 删除合同材料信息
     *
     * @param deletedDto
     * @return
     */
    @PostMapping("/material/deleted")
    public YResult<String> deletedMaterialInfo(@RequestBody SoSupplyMaterialDeletedDto deletedDto) {
        return soSupplyOrderService.deletedMaterialInfo(deletedDto);
    }


    /**
     * 验收
     *
     * @param soSupplyDto
     * @return
     */

    @PostMapping("/confirm/finish")
    public YResult<String> confirmFinish(@RequestBody SoSupplyDto soSupplyDto) {
        UserInfoRequest userInfo = BaseContext.getUserInfo();
        soSupplyDto.setUserId(userInfo.getId());
        soSupplyDto.setRealName(userInfo.getRealName());
        return soSupplyOrderService.confirmFinish(soSupplyDto);
    }

    /**
     * 导出文件
     *
     * @return
     */

    @GetMapping("/export/file")
    public YResult<String> exportFile(SoSupplyDto soSupplyDto, HttpServletResponse response) {
        try {
            List<SupplyExcelDto> contractMaterialExportDtoList =  soSupplyService.export(soSupplyDto);
            try {
                // 这里URLEncoder.encode可以防止中文乱码
                String fileName = URLEncoder.encode("sosupply", String.valueOf(StandardCharsets.UTF_8))+".xlsx";
//                response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
                //设置sheet名
                ExportParams params = new ExportParams();
                params.setSheetName("清单信息模版");
                //设置标题
//                params.setTitle("商品信息");
                // 这里需要设置不关闭流
                Workbook workbook = ExcelExportUtil.exportExcel(params, SupplyExcelDto.class, contractMaterialExportDtoList);
                //输出流
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                workbook.write(bos);
                byte[] bytes = bos.toByteArray();
                bos.close();
                try {
                    FileInfoDto fileInfoDto = AliOssUtil.upload(bytes,
                            fileName, null);
                    if (null != fileInfoDto) {
                        return YResult.success(fileInfoDto.getLink());
                    } else {
                        return YResult.error("连接文件服务器失败，请重试");
                    }
                } catch (Exception e) {
                    return YResult.error("下载失败，请重试");
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }catch (Exception e) {
            log.error("导出清单信息失败",e);
        }
        return YResult.error("导出清单信息失败");
    }
}
